//
//  TestTool.swift
//  GLUZSwift
//
//  Created by yu on 2025/3/25.
//

import Foundation
import SwiftyUserDefaults

class TestTool {
    
    /// 在任何界面弹出账号选择弹窗
    /// - Parameters:
    ///   - sourceVC: 当前视图控制器
    ///   - sourceView: 弹窗锚点视图 (iPad 必需)
    ///   - onSelect: 选中回调
    static func showAccountPicker(
        from sourceVC: UIViewController,
//        sourceView: UIView? = nil,
        onSelect: @escaping (TestAccount) -> Void
    ) {
        // 主线程安全
        DispatchQueue.main.async {
            let accountListVC = AccountListViewController()
            accountListVC.onAccountSelected = onSelect
            
            // 配置弹窗样式
            let navController = UINavigationController(rootViewController: accountListVC)
            navController.modalPresentationStyle = .popover
            
//            // 适配 iPad
//            if let popover = navController.popoverPresentationController {
//                popover.sourceView = sourceView ?? sourceVC.view
//                popover.sourceRect = sourceView?.bounds ?? CGRect(x: sourceVC.view.bounds.midX, y: sourceVC.view.bounds.midY, width: 0, height: 0)
//                popover.permittedArrowDirections = [.up, .down]
//            }
            
            sourceVC.present(navController, animated: true)
        }
    }

}

// MARK: - 账号数据模型
struct TestAccount: Codable, Equatable {
    // 核心字段
    var country: Int
    let username: String        // 唯一标识 (不可修改)
    var password: String
    var displayName: String     // 显示名称 (可修改)
    var note: String            // 备注信息 (可修改)
    var isDefault: Bool         // 是否默认账号 (不可修改)
    var lastLoginDate: Date? // 新增登录时间属性
    
    // 初始化方法
    init(
        country: Int,
        username: String,
        password: String,
        displayName: String? = nil,
        note: String? = nil,
        isDefault: Bool = false,
        lastLoginDate: Date? = nil
    ) {
        self.country = country
        self.username = username
        self.password = password
        self.displayName = displayName ?? username
        self.note = note ?? ""
        self.isDefault = isDefault
        self.lastLoginDate = lastLoginDate
    }
    
    // 通过 username 判等 (唯一标识)
    static func == (lhs: TestAccount, rhs: TestAccount) -> Bool {
        return lhs.username == rhs.username
    }
}

// MARK: - 账号管理核心类
final class TestAccountManager {
    
    // MARK: - 单例模式
    static let shared = TestAccountManager()
    private init() {}
    
    // MARK: - 存储配置
    private let userDefaultsKey = "SavedTestAccounts"
    
    // MARK: - 默认账号列表 (开发阶段预设)
    private let defaultAccounts: [TestAccount] = [
        TestAccount(
            country: 0,
            username: "15112345678",
            password: "qwe123456",
            displayName: "我的",
            note: "普通用户权限",
            isDefault: true
        ),
        TestAccount(
            country: 0,
            username: "14799999999",
            password: "12345678",
            displayName: "",
            note: "供应商",
            isDefault: true
        ),
        TestAccount(
            country: 0,
            username: "14799998888",
            password: "12345678",
            displayName: "",
            note: "采购商",
            isDefault: true
        ),
        TestAccount(
            country: 0,
            username: "14799994444",
            password: "12345678",
            displayName: "",
            note: "翻译",
            isDefault: true
        ),
//        TestAccount(
//            country: 0,
//            username: "admin@example.com",
//            password: "admin",
//            displayName: "管理员",
//            note: "系统管理员权限",
//            isDefault: true
//        )
    ]
    
    // MARK: - 公开方法
    
    /// 获取所有可用账号 (默认账号 + 用户保存的账号)
    func getAllAccounts() -> [TestAccount] {
        let savedAccounts = loadSavedAccounts()
        return mergeAccounts(defaults: defaultAccounts, saved: savedAccounts)
    }
    
    /// 添加新账号 (自动去重)
//    func addNewAccount(_ account: TestAccount) {
//        var savedAccounts = loadSavedAccounts()
//        guard !savedAccounts.contains(account) else { return }
//        savedAccounts.append(account)
//        saveAccounts(savedAccounts)
//    }
    
    // MARK: - 登录后自动保存/更新账号
//    func handleLoginAutoSave(
//        country: Int,
//        username: String,
//        password: String,
//        displayName: String? = nil,
//        note: String? = nil
//    ) {
//        // 构造当前登录账号对象
//        var currentAccount = TestAccount(
//            country: country,
//            username: username,
//            password: password,
//            displayName: displayName,
//            note: note
//        )
//        
//        // 获取所有已保存账号（不包含默认账号）
//        var savedAccounts = loadSavedAccounts()
//        
//        // 检查是否已存在相同用户名的账号
//        if let index = savedAccounts.firstIndex(where: { $0.username == username }) {
//            
//            updateAccount(username: <#T##String#>)
//            // 存在则校验密码
//            if savedAccounts[index].password != password {
//                // 密码不同时更新密码
//                savedAccounts[index].password = password
//                savedAccounts[index].lastLoginDate = Date()
//                saveAccounts(savedAccounts)
//                print("账号 \(username) 密码已更新")
//            }
//        } else {
//            // 新账号直接添加
//            currentAccount.lastLoginDate = Date()
//            savedAccounts.append(currentAccount)
//            saveAccounts(savedAccounts)
//            print("新账号 \(username) 已保存")
//        }
//    }
    
    
    /// 删除用户保存的账号
    func deleteSavedAccount(_ account: TestAccount) {
        var savedAccounts = loadSavedAccounts()
        savedAccounts.removeAll { $0 == account }
        saveAccounts(savedAccounts)
    }
    
    /// 更新账号信息 (支持密码/显示名称/备注)
    func updateAccount(
        username: String,
        newPassword: String? = nil,
        newDisplayName: String? = nil,
        newNote: String? = nil,
        newLoginDate: Date? = nil
    ) {
        var savedAccounts = loadSavedAccounts()
        
        // 查找需要更新的账号索引
        guard let index = savedAccounts.firstIndex(where: { $0.username == username }) else {
            // 如果尝试更新默认账号，则转换为用户账号
            if let defaultAccount = defaultAccounts.first(where: { $0.username == username }) {
                var convertedAccount = defaultAccount
                convertedAccount.isDefault = false
                convertedAccount.password = newPassword ?? defaultAccount.password
                convertedAccount.displayName = newDisplayName ?? defaultAccount.displayName
                convertedAccount.note = newNote ?? defaultAccount.note
                savedAccounts.append(convertedAccount)
                saveAccounts(savedAccounts)
            }
            return
        }
        
        // 增量更新字段
        if let newPassword = newPassword {
            savedAccounts[index].password = newPassword
        }
        if let newDisplayName = newDisplayName {
            savedAccounts[index].displayName = newDisplayName
        }
        if let newNote = newNote {
            savedAccounts[index].note = newNote
        }
        if let newLoginDate = newLoginDate {
            savedAccounts[index].lastLoginDate = newLoginDate
        }
        
        saveAccounts(savedAccounts)
    }
    
    // MARK: - 私有方法
    
    /// 加载用户保存的账号
    private func loadSavedAccounts() -> [TestAccount] {
        guard let data = UserDefaults.standard.data(forKey: userDefaultsKey) else { return [] }
        do {
            return try JSONDecoder().decode([TestAccount].self, from: data)
        } catch {
            print("账号加载失败: \(error)")
            return []
        }
    }
    
    /// 持久化保存账号列表
    private func saveAccounts(_ accounts: [TestAccount]) {
        do {
            let data = try JSONEncoder().encode(accounts)
            UserDefaults.standard.set(data, forKey: userDefaultsKey)
        } catch {
            print("账号保存失败: \(error)")
        }
    }
    
    /// 合并默认账号和用户保存的账号 (用户数据优先)
    private func mergeAccounts(defaults: [TestAccount], saved: [TestAccount]) -> [TestAccount] {
        
        return saved + defaults.filter { defaultAcc in
                !saved.contains(where: { $0.username == defaultAcc.username })
            }
//        var merged = defaults
//        for savedAccount in saved {
//            if let index = merged.firstIndex(of: savedAccount) {
//                merged[index] = savedAccount  // 用户数据覆盖默认数据
//            } else {
//                merged.append(savedAccount)   // 添加新账号
//            }
//        }
//        return merged
    }
}

extension TestAccountManager {
    
    // MARK: - 登录后自动保存/更新账号
        func handleLoginAutoSave(
            country: Int,
            username: String,
            password: String,
            displayName: String? = nil,
            note: String? = nil
        ) {
            // 判断是否为默认账号
            let isDefaultAccount = defaultAccounts.contains { $0.username == username }
            
            // 转换为用户保存账号（如果需要）
            if isDefaultAccount {
                convertDefaultToSavedAccount(
                    username: username,
                    password: password,
                    country: country,
                    displayName: displayName,
                    note: note
                )
            } else {
                updateOrAddSavedAccount(
                    username: username,
                    password: password,
                    country: country,
                    displayName: displayName,
                    note: note
                )
            }
        }
        
        // MARK: - 转换默认账号为用户保存账号
        private func convertDefaultToSavedAccount(
            username: String,
            password: String,
            country: Int,
            displayName: String?,
            note: String?
        ) {
            guard let defaultAccount = defaultAccounts.first(where: { $0.username == username }) else {
                return
            }
            
            var savedAccounts = loadSavedAccounts()
            
            // 移除可能存在的旧用户保存副本
            savedAccounts.removeAll { $0.username == username }
            
            // 创建新用户保存账号（继承默认数据，覆盖可修改字段）
            let newSavedAccount = TestAccount(
                country: country,
                username: defaultAccount.username,
                password: password,
                displayName: displayName ?? defaultAccount.displayName,
                note: note ?? defaultAccount.note,
                isDefault: false,           // 标记为用户保存
                lastLoginDate: Date()       // 更新登录时间
            )
            
            savedAccounts.append(newSavedAccount)
            saveAccounts(savedAccounts)
        }
        
        // MARK: - 更新或新增用户保存账号
        private func updateOrAddSavedAccount(
            username: String,
            password: String,
            country: Int,
            displayName: String?,
            note: String?
        ) {
            var savedAccounts = loadSavedAccounts()
            
            if let index = savedAccounts.firstIndex(where: { $0.username == username }) {
                // 更新现有账号
                var account = savedAccounts[index]
                account.password = password
                account.displayName = displayName ?? account.displayName
                account.note = note ?? account.note
                account.lastLoginDate = Date()
                savedAccounts[index] = account
            } else {
                // 添加新账号
                let newAccount = TestAccount(
                    country: country,
                    username: username,
                    password: password,
                    displayName: displayName,
                    note: note,
                    isDefault: false
                )
                savedAccounts.append(newAccount)
            }
            
            saveAccounts(savedAccounts)
        }
    
    
    /// 更新账号信息 - 列表使用
    func updateAccount(
            username: String,
            newPassword: String? = nil,
            newDisplayName: String? = nil,
            newNote: String? = nil,
            newCountry: Int? = nil,
            newLoginDate: Date? = nil
        ) {
            var savedAccounts = loadSavedAccounts()
            
            guard let index = savedAccounts.firstIndex(where: { $0.username == username }) else {
                // 如果处理默认账号，则进行转换
                if let defaultAccount = defaultAccounts.first(where: { $0.username == username }) {
                    convertDefaultToSavedAccount(
                        username: username,
                        password: defaultAccount.password, // 使用传入参数或其他默认值
                        country: newCountry ?? defaultAccount.country,
                        displayName: newDisplayName ?? defaultAccount.displayName,
                        note: newNote ?? defaultAccount.note
                    )
                }
                return
            }
            
            // 增量更新字段
            savedAccounts[index].password = newPassword ?? savedAccounts[index].password
            savedAccounts[index].displayName = newDisplayName ?? savedAccounts[index].displayName
            savedAccounts[index].note = newNote ?? savedAccounts[index].note
            savedAccounts[index].country = newCountry ?? savedAccounts[index].country
            savedAccounts[index].lastLoginDate = newLoginDate ?? savedAccounts[index].lastLoginDate
            
            saveAccounts(savedAccounts)
        }
    
    
    
    /// 获取排序后的账号列表
    func getAllSortTimeAccounts() -> [TestAccount] {
        let accounts = getAllAccounts()
        return accounts.sorted { $0.lastLoginDate ?? Date(timeIntervalSince1970: 0) > $1.lastLoginDate ?? Date(timeIntervalSince1970: 0) } // 按时间降序排列
    }
    
    /// 快速创建配置好的账号列表控制器
    /// - Parameter onSelect: 账号选中回调
    func createAccountListViewController(
        onSelect: @escaping (TestAccount) -> Void
    ) -> AccountListViewController {
        let vc = AccountListViewController()
        vc.onAccountSelected = onSelect
        return vc
    }
    
    /// 打印所有账号详细信息 (包含默认账号和用户保存的账号)
        func printAllAccountsInfo() {
            let accounts = getAllAccounts()
            
            let divider = "----------------------------------------"
            var output = "\n\(divider)\n    当前所有测试账号信息 (\(accounts.count) 个)\n\(divider)"
            
            for (index, account) in accounts.enumerated() {
                output += """
                \n[账号 \(index + 1)]
                用户名: \(account.username)
                显示名称: \(account.displayName)
                密码: \(account.password)
                备注: \(account.note)
                类型: \(account.isDefault ? "默认账号" : "用户保存")
                """
            }
            output += "\n\(divider)"
            print(output)
            var copyCode = "复制保存到代码默认输出\n\(divider)"
            for account in accounts {
                copyCode += """
                \nTestAccount(
                    country: \(account.country),
                    username: "\(account.username)",
                    password: "\(account.password)",
                    displayName: "\(account.displayName)",
                    note: "\(account.note)",
                    isDefault: \(account.isDefault ? "true" : "false")
                ),
                """
            }
            copyCode += "\n\(divider)"
            print(copyCode)
        }
}


// 在视图控制器中调用示例
class AccountListViewController: UITableViewController {
    
    private var accounts: [TestAccount] = []
    var onAccountSelected: ((TestAccount) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        accounts = TestAccountManager.shared.getAllSortTimeAccounts()
        title = "测试账号库"
        navigationItem.rightBarButtonItem = UIBarButtonItem(
                    image: UIImage(systemName: "printer"),
                    style: .plain,
                    target: self,
                    action: #selector(printAllAccounts)
                )
        
        setupTableView()
        
    }
    
    private func setupTableView() {
        tableView.register(AccountCell.self, forCellReuseIdentifier: "cell")
        tableView.rowHeight = 90
    }
    
    // MARK: - TableView 数据源
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return accounts.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountCell
        let account = accounts[indexPath.row]
//        cell.configure(with: account)
        cell.textLabel?.text = account.displayName
        // 副标题显示时间
        let timeStr: String
        if let lastDate = account.lastLoginDate {
            timeStr = formatLoginTime(lastDate)
        } else {
            timeStr = "暂无"
        }
//        cell.timeLabel.text = "最后登录时间: \(timeStr)\n"
        
        cell.detailTextLabel?.text = "账号: \(account.username)\n备注: \(account.note)\n最后登录时间: \(timeStr)\n"
        cell.detailTextLabel?.numberOfLines = 3
        
        
        cell.onEdit = { [weak self] in
            self?.showEditAlert(for: account)
        }
        
        
        
        return cell
    }
    
    // MARK: - 行选择
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let account = accounts[indexPath.row]
        onAccountSelected?(account)
        dismiss(animated: true)
    }
    
    // MARK: - 编辑弹窗
    private func showEditAlert(for account: TestAccount) {
        let alert = UIAlertController(
            title: "编辑账号",
            message: nil,
            preferredStyle: .alert
        )
        
        alert.addTextField { $0.text = account.displayName }
        alert.addTextField { $0.text = account.note }
        
        alert.addAction(UIAlertAction(title: "保存", style: .default) { _ in
            let newDisplayName = alert.textFields?[0].text ?? ""
            let newNote = alert.textFields?[1].text ?? ""
            TestAccountManager.shared.updateAccount(
                username: account.username,
                newDisplayName: newDisplayName,
                newNote: newNote
            )
            self.reloadData()
        })
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        present(alert, animated: true)
    }
    
    private func reloadData() {
        accounts = TestAccountManager.shared.getAllAccounts()
        tableView.reloadData()
    }
    
    // MARK: - 打印操作
    @objc private func printAllAccounts() {
        TestAccountManager.shared.printAllAccountsInfo()
        showPrintConfirmation()
    }
    
    // MARK: - 显示打印完成提示
    private func showPrintConfirmation() {
        let alert = UIAlertController(
            title: "账号信息已打印",
            message: "请在 Xcode 控制台查看详细数据",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
    
    private func formatLoginTime(_ date: Date) -> String {
        let calendar = Calendar.current
        if calendar.isDateInToday(date) {
            return "今天 \(DateFormatter.relativeFormatter.string(from: date))"
        } else if calendar.isDateInYesterday(date) {
            return "昨天 \(DateFormatter.relativeFormatter.string(from: date))"
        } else {
            return DateFormatter.relativeFormatter.string(from: date)
        }
    }
    
}

// 自定义 Cell
class AccountCell: UITableViewCell {
    var onEdit: (() -> Void)?
    
//    lazy var timeLabel: UILabel = {
//        let label = UILabel()
//        label.font = UIFont.systemFont(ofSize: 14)
//        label.textColor = .black
//        return label
//    }()
    
    private lazy var editButton: UIButton = {
        let btn = UIButton(type: .infoDark)
        btn.setImage(UIImage(systemName: "pencil"), for: .normal)
        btn.addTarget(self, action: #selector(editTapped), for: .touchUpInside)
//        btn.backgroundColor = .lightGray
        return btn
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        accessoryView = editButton
        editButton.size = CGSizeMake(40, 40)
        
//        contentView.addSubview(timeLabel)
//        timeLabel.translatesAutoresizingMaskIntoConstraints = false
//        NSLayoutConstraint .activate([
//            timeLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20),
//            timeLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12)
//        ])
        
    }
    
//    func configure(with account: TestAccount) {
//        textLabel?.text = account.displayName
//        // 副标题显示时间
//        let timeStr: String
//        if let lastDate = account.lastLoginDate {
//            let dateFormatter = DateFormatter()
//            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
//            timeStr =  "\(dateFormatter.string(from: lastDate))"
//        } else {
//            timeStr = "暂无"
//        }
//        
//        detailTextLabel?.text = "账号: \(account.username)\n最后登录时间: \(timeStr)\n备注: \(account.note)"
//        detailTextLabel?.numberOfLines = 3
//    }
    
    @objc private func editTapped() {
        onEdit?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// DateFormatter+Extensions.swift
extension DateFormatter {
    static let relativeFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.doesRelativeDateFormatting = true
        formatter.dateStyle = .short
        formatter.timeStyle = .short
        return formatter
    }()
}
